package com.lagou.sqlSession;

import com.lagou.config.BoundlSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:zhouyong@cqyyt.com">zy</a>
 * @version 1.0
 * @date 2020/12/5 14:44
 */
public class simpleExcutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // jdbc
        // 1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql,select * from user where id = #{id} and username = #{username}
            //对sql进行转换select * from user where id = ? and username = ?
        String sql = mappedStatement.getSql();
        BoundlSql boundlSql = getBoundSql(sql);

        //3.获取预处理对象 ：preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundlSql.getParseSql());

        //4.设置参数
            //获取到参数的路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappings = boundlSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            //防止私有，设置暴力访问
            declaredField.setAccessible(true);
            //  Object... params就是一个可变参数组, params[0]拿的就是user
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);

        }

        //5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<Object>();
        //6.封装返回的结果集
        while ( resultSet.next() ){
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //获取字段值
                Object value = resultSet.getObject(columnName);
                //通过反射把数据封装到对象中
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke( o,value );
            }
            objects.add(o);
        }

        return (List<E>) objects;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if ( paramterType != null ){
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作，1.先将#{}用？代理，2.将#{}里面的值进行存储
     * @param sql
     * @return
     */
    public BoundlSql getBoundSql(String sql){
        //标记处理器
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundlSql boundlSql = new BoundlSql(parseSql,parameterMappings);
        return boundlSql;
    }
}
